package com.tutor.lzm.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.lidroid.xutils.BitmapUtils;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.tutor.lzm.AppSession;
import com.tutor.lzm.R;
import com.tutor.lzm.app.CommonValue;
import com.tutor.lzm.app.Constant;
import com.tutor.lzm.bean.TeacherDetailInfo;
import com.tutor.lzm.function.authenticate.act.AuditResultsAct;
import com.tutor.lzm.function.authenticate.act.CertificationTeacherAct;
import com.tutor.lzm.function.basic.SettingActivity;
import com.tutor.lzm.function.parents.DeliveryTeacherAct;
import com.tutor.lzm.function.teacher.act.CollectionTeacherAct;
import com.tutor.lzm.function.teacher.act.IamTeacherAct;
import com.tutor.lzm.function.teacher.act.MyTeacherAct;
import com.tutor.lzm.function.tutor.TutorHistoryAct;
import com.tutor.lzm.http.BaseResponse;
import com.tutor.lzm.http.HttpClient;
import com.tutor.lzm.http.request.TeacherDetailInfoRequest;
import com.tutor.lzm.http.request.UploadHeadImageRequest;
import com.tutor.lzm.oss.UICallback;
import com.tutor.lzm.utils.ImageUtils;
import com.tutor.lzm.utils.ProjectStringUtils;
import com.tutor.lzm.utils.UserOssUtils;
import com.tutor.lzm.view.CircleImageView;
import com.tutor.syslib.Logs;
import com.tutor.syslib.impl.OneChoiceImpl;
import com.tutor.syslib.util.FileUtils;
import com.tutor.syslib.util.MessageTools;
import com.tutor.syslib.view.RichTextView;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.tutor.lzm.R.id.imageView;

/**
 * Created by zzgpc on 2017-8-24.
 */

public class PersonFragment extends BaseFragment {
    @BindView(R.id.img_my)
    CircleImageView imgMy;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_introduction)
    TextView tvIntroduction;
    @BindView(R.id.ll_my_collection)
    LinearLayout llMyCollection;
    @BindView(R.id.ll_my_release)
    LinearLayout llMyRelease;
    @BindView(R.id.ll_my_evaluation)
    LinearLayout llMyEvaluation;
    @BindView(R.id.ly_my_intention)
    LinearLayout lyMyIntention;
    @BindView(R.id.ly_intention_who)
    LinearLayout lyIntentionWho;
    @BindView(R.id.ly_my_teacher)
    LinearLayout lyMyTeacher;
    @BindView(R.id.ly_customer_phone)
    LinearLayout lyCustomerPhone;
    @BindView(R.id.ly_teacher_recruit)
    LinearLayout lyTeacherRecruit;
    @BindView(R.id.ly_setting)
    LinearLayout lySetting;
    Unbinder unbinder;
    @BindView(R.id.tv_status)
    RichTextView tvStatus;
    @BindView(R.id.ly_iam_teacher)
    LinearLayout lyIamTeacher;
    @BindView(R.id.ly_my_resume)
    LinearLayout lyMyResume;
    @BindView(R.id.ly_become_teacher)
    LinearLayout lyBecomeTeacher;
    private UserOssUtils ossUtils;
    private String headImageUrl;

    /**
     * 成为老师的审核状态
     * <p>
     * 1	待审核
     * 2	审核通过
     * 3	审核未通过
     */
    private int reviewStatus = 0;

    @Override
    public int getFragmentLayout() {
        return R.layout.fragment_person;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        contentView = inflater.inflate(getFragmentLayout(), container, false);
        unbinder = ButterKnife.bind(this, contentView);
        super.onCreateView(inflater, container, savedInstanceState);
        ossUtils = new UserOssUtils(getContext(), null);
        ossUtils.initOssData();
        return contentView;
    }


    @Override
    protected void initView(Bundle bundle) {
        super.initView(bundle);
        int userStatus = AppSession.getInstance().getUserInfo().status;
        tvStatus.setVisibility(View.VISIBLE);
        tvStatus.setText(ProjectStringUtils.getTeacherType(userStatus));
        headImageUrl = UserOssUtils.uploadUrl + Constant.headImage + AppSession.getInstance().getUserId() + ".png";
        Picasso.with(getContext())
                .load(headImageUrl)
                .memoryPolicy(MemoryPolicy.NO_CACHE)
                .networkPolicy(NetworkPolicy.NO_CACHE)
                .into(imgMy);

        tvName.setText(AppSession.getInstance().getUserInfo().nickName);
        reviewStatus = AppSession.getInstance().getUserInfo().reviewStatus;
        if (reviewStatus == 0) {
            lyIamTeacher.setVisibility(View.GONE);
            lyBecomeTeacher.setVisibility(View.VISIBLE);
        } else {
            lyIamTeacher.setVisibility(View.VISIBLE);
            lyBecomeTeacher.setVisibility(View.GONE);
        }
    }

    private TeacherDetailInfo teacherInfo;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {// 不在最前端界面显示
        } else {// 重新显示到最前端中
            reviewStatus = AppSession.getInstance().getUserInfo().reviewStatus;
            if (reviewStatus == 0) {
                lyIamTeacher.setVisibility(View.GONE);
                lyBecomeTeacher.setVisibility(View.VISIBLE);
            } else {
                lyIamTeacher.setVisibility(View.VISIBLE);
                lyBecomeTeacher.setVisibility(View.GONE);
            }
//            boolean isTeacher = AppSession.getInstance().isTeacher();
//            if (isTeacher) {
//                lyIamTeacher.setVisibility(View.VISIBLE);
//                lyBecomeTeacher.setVisibility(View.GONE);
//            } else {
//                lyIamTeacher.setVisibility(View.GONE);
//                lyBecomeTeacher.setVisibility(View.VISIBLE);
//            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //解绑ButterKnife
        unbinder.unbind();
    }

    @OnClick({R.id.img_my, R.id.ll_my_collection, R.id.ll_my_release, R.id.ly_become_teacher, R.id.ll_my_evaluation, R.id.ly_iam_teacher, R.id.ly_my_intention, R.id.ly_intention_who, R.id.ly_my_resume, R.id.ly_my_teacher, R.id.ly_customer_phone, R.id.ly_teacher_recruit, R.id.ly_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_my:
                openCamera();
                break;
            case R.id.ll_my_collection:
                //我的收藏
                CollectionTeacherAct.start(getContext());
                break;
            case R.id.ll_my_release:
                //我的发布
                TutorHistoryAct.start(getContext());
                break;
            case R.id.ll_my_evaluation:
                //我的评价
                MessageTools.showDialogOk(getContext(), "该功能暂未开放，敬请期待...");
                break;
            case R.id.ly_become_teacher:
                //认证成为老师
                CertificationTeacherAct.start(getContext(), "1");
                break;
            case R.id.ly_iam_teacher:
                //我是老师
                startIamTeacher(reviewStatus);
                break;
            case R.id.ly_my_intention:
                //我的意向

                break;
            case R.id.ly_intention_who:
                //谁有意向
                DeliveryTeacherAct.start(getContext());
                break;
            case R.id.ly_my_resume:
                //我的简历
                IamTeacherAct.start(getContext());
                break;
            case R.id.ly_my_teacher:
                //我的老师
                MyTeacherAct.start(getContext());
                break;
            case R.id.ly_customer_phone:
                //客服电话
                break;
            case R.id.ly_teacher_recruit:
                //老师招募
                break;
            case R.id.ly_setting:
                //设置
                SettingActivity.start(getContext());
                break;
        }
    }


    /**
     * 跳转我是老师
     *
     * @param status
     */
    private void startIamTeacher(int status) {
        if (status == 2) {
            IamTeacherAct.start(getContext());
        } else {
            AuditResultsAct.start(getContext(), status);
        }
    }

    /**
     * 拍照弹出框
     */
    private void openCamera() {
        ArrayList<String> list = new ArrayList<>();
        list.add("相册");
        list.add("拍照");

        MessageTools.showOneChoiceDialog(getContext(), "请选择", list, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                switch (position) {
                    case 0:
                        // 从相册选取
                        ImageUtils.choicePicture(getActivity());

                        break;
                    case 1:
                        // 拍照
                        // 判断存储卡是否可以用，可用进行存储
                        if (ImageUtils.hasSdcard()) {
                            ImageUtils.takePicture(getActivity());
                        }
                        break;
                }
            }
        });

    }

    /**
     * 上传图片
     * 命名
     */
    private void upLoadImg(final String filePath) {
        mAct.showMyDialog("正在上传图片");

        String url = Constant.headImage + AppSession.getInstance().getUserId() + ".png";
        ossUtils.asyncTaskUpload(url, filePath, getPutCallback(imgMy, filePath, UserOssUtils.uploadUrl + headImageUrl));


    }

    private void upLoadHeadImage(final String imageName, final String url) {
        UploadHeadImageRequest request = new UploadHeadImageRequest();
        request.userId = AppSession.getInstance().getUserId();
        request.headImageUrl = url;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {

                mAct.closeDialog();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                mAct.closeDialog();
            }
        });

    }


    // 普通上传回调
    public UICallback<PutObjectRequest, PutObjectResult> getPutCallback(final ImageView view, final String imageName, final String url) {

        return new UICallback<PutObjectRequest, PutObjectResult>(ossUtils.UIDispatcher) {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Logs.d(tag, "UploadSuccess");

                addCallback(new Runnable() {
                    @Override
                    public void run() {
                        File file = new File(imageName);
                        Picasso.with(getContext())
                                .load(file)
                                .memoryPolicy(MemoryPolicy.NO_CACHE)
                                .networkPolicy(NetworkPolicy.NO_CACHE)
                                .into(imgMy);
                        upLoadHeadImage(imageName, url);

                    }
                }, null);

                super.onSuccess(request, result);
            }


            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Logs.e("ErrorCode", serviceException.getErrorCode());
                    Logs.e("RequestId", serviceException.getRequestId());
                    Logs.e("HostId", serviceException.getHostId());
                    Logs.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);

                mHandler.sendEmptyMessage(Constant.MSG_LOAD_ERROR);
                ossUtils.ossService.stopPutLoad();
                // mHandler.sendEmptyMessage( Constant.MSG_LOAD_ERROR );
//                onFailure(request, clientExcepion, serviceException);
            }
        };
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case Constant.MSG_LOAD_SUCCES:

                    break;
                case Constant.MSG_LOAD_ERROR:
                    mAct.closeDialog();
                    MessageTools.showToast(getContext(), "图片上传失败！");
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constant.RESULT_REQUEST_CODE) {
            //图片截取
            if (data != null) {
                setPersonImage(data);
            } else {
                return;
//                setPersonImage(data, tempFile.getPath());
            }
            return;
        }
        if (resultCode == getActivity().RESULT_OK) {
            if (requestCode == Constant.REQUEST_PICTURE) {
                // 相册
                Uri uri = data.getData();
                ImageUtils.startPhotoZoom(getContext(), uri);
//                setPhotoImage(uri);
                //sendImage(uri);
            } else if (requestCode == Constant.REQUEST_CODE_BASE) {
                if (data != null && data.getData() != null) {
                    // 相机 并且获取到arg2
                    Uri uri = data.getData();
//                    setPhotoImage(uri);
                    //   sendImage(uri);
                    ImageUtils.startPhotoZoom(getContext(), uri);
                } else {
                    // 相机，获取不到intent数据
                    Uri uri = Uri.parse(CommonValue.openCameraUri);
//                    setPhotoImage(uri);
                    //  sendImage(uri);
                    ImageUtils.startPhotoZoom(getContext(), uri);
                }
            }
        }

    }

    private void setPersonImage(Intent data) {
        Bitmap bitmap;
        if (data != null) {
            Bundle extras = data.getExtras();
            bitmap = extras.getParcelable("data");
        } else {
            bitmap = null;
//            bitmap = BitmapUtils.getBitmapForFilePath(path);
        }
        if (bitmap == null) {
            MessageTools.showToast(getContext(), "获取图片失败");
            return;
        }
//        File file = new File(Environment.getExternalStorageDirectory(), mAct.appSession.getAccoundId() + ".png");

//        final String albumPath = FileUtils.getRealPathFromURI(getContext(), uri);
        File uploadFile = new File(FileUtils.getAppPath(), AppSession.getInstance().getUserId() + ".png");
        final String albumPath = uploadFile.getPath();
        FileUtils.compressAndSaveBitmapToFile(bitmap, albumPath, 100);
//        BitmapDrawable drawable = new BitmapDrawable(BitmapUtils.getBitmapForFilePath(albumPath));
//        imgMy.setImageDrawable(drawable);

        upLoadImg(albumPath);


    }


//    /**
//     * 解析uri是否存在
//     *
//     * @param uri
//     */
//    private void setPhotoImage(Uri uri) {
//        upLoadImg(uri.getPath());
//
////        String albumPath = ImageUtils.getPath(getContext(), uri);
////        if (TextUtils.isEmpty(albumPath)) {
////            MessageTools.showToast(getContext(), "获取照片失败，请重新拍照！");
////            return;
////        }
////
////        File file = new File(albumPath);
////        if (!file.exists()) {
////            MessageTools.showToast(getContext(), "获取照片失败，请重新拍照！");
////            return;
////
////        }
////        upLoadImg(albumPath);
//
//    }
}
